package com.xdxc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xdxc.model.entity.SysUser;
import com.xdxc.model.entity.User;
import com.xdxc.exception.CustomException;
import com.xdxc.response.Result;
import com.xdxc.service.AuthService;
import com.xdxc.service.SysUserService;
import com.xdxc.service.UserService;
import com.xdxc.utils.EncryptionUtils;
import com.xdxc.vo.LoginAdminVo;
import com.xdxc.vo.RegisterAdmin;
import com.xdxc.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Base64;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserService userService;


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 普通用户登录（通过邮箱）
    @Override
    public String loginByEmail(String email, String password) {
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail,email));
        if (user == null || !user.getPassword().equals(password)) {
            throw new CustomException(1000,"邮箱或密码错误");
        }

        return null;
    }

    // 管理员登录（通过用户名）
    @Override
    public Result loginByUserName(LoginAdminVo loginAdminVo) {
        String username=   loginAdminVo.getUserName();
        String password=   loginAdminVo.getPassword();
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, username)); // 明确指定需要查询的字段
        if (sysUser == null) {
            return Result.error(401, "用户不存在");
        }

        byte[] saltBytes = Base64.getDecoder().decode(sysUser.getSalt());
        boolean isVerified = EncryptionUtils.verifyPbkdf2Hash(
                password.toCharArray(),
                sysUser.getPassword(),
                saltBytes
        );
        if (!isVerified) {
            return Result.error(401, "账号或密码错误");
        }
        return Result.success(sysUser);
    }



    @Transactional
    @Override
    public boolean registerByUsername(RegisterAdmin registerAdmin) {
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName,registerAdmin.getUserName()));
        if (sysUser != null ) {
            return false;
        }
        byte[] salt = EncryptionUtils.generateSalt();
        String hashedPassword = EncryptionUtils.pbkdf2Hash(registerAdmin.getPassword().toCharArray(), salt);
        SysUser sysUser1=SysUser.builder()
                .userName(registerAdmin.getUserName())
                .password(hashedPassword)
                .roles(registerAdmin.getRoles())
                .salt(java.util.Base64.getEncoder().encodeToString(salt))
                .build();

     boolean bo= sysUserService.save(sysUser1);
        return bo;
    }

    @Override
    public User loginByEmail(UserLoginVo userLoginVo) {

        String email=   userLoginVo.getEmail();
        String password=   userLoginVo.getPassword();
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getEmail, email)); // 明确指定需要查询的字段
        if (user == null) {
            throw  new CustomException(401,"账号或密码错误");
        }

        byte[] saltBytes = Base64.getDecoder().decode(user.getSalt());
        boolean isVerified = EncryptionUtils.verifyPbkdf2Hash(
                password.toCharArray(),
                user.getPassword(),
                saltBytes
        );
        if (!isVerified) {
            throw  new CustomException(401,"账号或密码错误");
        }
        user.setPassword(null);
        user.setSalt(null);
        return user;
    }



}